<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Cache\RateLimiter;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Http\Request;

class RateLimiterMiddleware
{
    protected $auth;

    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * 限流
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {

        $limiterKey = md5($this->auth->guard('h5')->id() . $request->getClientIp());
        //$limiterKey = md5($this->auth->guard('h5')->id() . $request->getClientIp() . $request->getPathInfo());
        $rateLimiter = app()->make(RateLimiter::class);
        if ($rateLimiter->tooManyAttempts($limiterKey, 15)) {
            abort(400, '您的小手累了，休息一会儿吧');
        }
        $rateLimiter->hit($limiterKey, 30);

        return $next($request);
    }
}
